<template>
  <div class="rent_main">
    <v-header head-title="发布房屋租售" goBack="true" house-publish="发布"></v-header>
    <div class="text_content">
      <mt-field placeholder="例如出租17幢2单元1003室114方1" type="textarea" rows="4" v-model="houseDetail"></mt-field>
    </div>
    <div class="vue-upload-img-multiple">
      <ul>
        <li v-show="image && !isIOS" v-for="(image,index) in images.localId" :key="index">
          <div class="img_size">
            <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
            <!-- <img :src="image" @click="preview(index)" /> -->
            <span @click='delImage(index)' class="remove">x</span>
          </div>
        </li>
        <li v-show="image && isIOS" v-for="(image,index) in images.iosLocalId" :key="index">
          <div class="img_size">
            <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
            <!-- <img :src="image" @click="preview(index)" /> -->
            <span @click='delImageIOS(index)' class="remove">x</span>
          </div>
        </li>
        <li class="input-container" @click="addImage()">
          <!-- <input type="file" @change="onFileChange" accept="image/gif,image/jpeg,image/jpg,image/png" class="file-input"
                 multiple> -->
        </li>
      </ul>
    </div>
    <div @click="saveImagesData()">上传</div>
    <ul>
      <li v-for="item in url" style="float: left; margin-right: 5px;">
        <img :src="item" alt="" width="40" height="40px">
      </li>
    </ul>
    <!--<button @click='addPic' style="margin-top: 40px; font-size: 20px;">上传</button>-->
  </div>
</template>
<style lang="scss">
  /*@import "../../common/sass/index.scss";*/

  .rent_main {
    width: 100%;
    padding-top: 40px;
    background-color: #fff;
    .text_content {
      padding: 10px;
      .mint-cell:first-child .mint-cell-wrapper {
        background-color: #f2f2f2;
        border-radius: 6px;
        .mint-field-core {
          resize: none;
          background-color: #f2f2f2;
          font-size: 14px;
        }
      }
    }
    .vue-upload-img-multiple {
      width: 100%;
      height: 100%;
      padding: 0 10px 10px;
      box-sizing: border-box;
      display: inline-block;
      ul {
        display: flex;
        flex-wrap: wrap;
        li {
          width: 25%;
          margin-top: 5px;
          .img_size {
            display: inline-block;
            position: relative;
            .picture {
              width: 70px;
              height: 70px;
              float: left;
              border-radius: 4px;
              background-repeat: no-repeat;
              background-size: cover;
            }
            .remove {
              position: absolute;
              top: -10px;
              right: -8px;
              width: 18px;
              height: 18px;
              z-index: 11;
              line-height: 18px;
              text-align: center;
              border-radius: 50%;
              // border-bottom: 1px solid #000;
              background-color: red;
              color: #fff;
              font-size: 15px;
            }
          }
        }
        .input-container {
          display: inline-block;
          background: url("../common/images/tianjiatupian@2x.png") no-repeat;
          width: 70px;
          height: 70px;
          background-size: 100% 100%;
          text-align: center;
        }
        // .file-input {
        //   height: 70px;
        //   width: 70px;
        //   opacity: 0;
        //   font-size: 0;
        // }
      }
    }
  }
</style>
<script>
  import headTop from '../header/Header.vue'
  import qs from 'qs'
  // import { Toast } from 'mint-ui'
  import wx from 'weixin-js-sdk'
  import commonUrl from '../../common/js/commonUrl.js'
  // import {saveImages} from '../../api/jianli.js'

  export default {
    name: 'Test',
    data () {
      return {
        images: {
          localId: [],
          iosLocalId: []
        },
        maxSize: 0,
        ready: false,
        isIOS: false,
        serverId: [],
        serverIds: '',
        url: []
      }
    },
    created() {
      // window.location.reload()
    },
    mounted () {
      // 初始化JSConfig
      const urlLink = `${commonUrl.apihost}index.php/wx/wx_jssdk/getSignPackage`
      let data = {
        url: window.location.href.split('#')[0]
      }
      this.$http.post(urlLink, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
        if (res.data.code === 200) {
          wx.config({
            debug: true,
            appId: res.data.data.appId,
            nonceStr: res.data.data.nonceStr,
            rawString: res.data.data.rawString,
            signature: res.data.data.signature,
            timestamp: res.data.data.timestamp,
            jsApiList: ['chooseImage', 'previewImage', 'getLocalImgData', 'uploadImage']
          })
          this.ready = true
        }
      })
    },
    components: {
      'v-header': headTop
    },
    methods: {
      addImage () {
        if (this.ready) {
          var self = this
          var currentSize = this.images.localId.length
          if (self.isIOS) {
            if (this.images.iosLocalId.length > 5) {
              alert('图片不能超过6张')
              return
            }
          } else {
            if (this.images.localId.length > 5) {
              alert('图片不能超过6张')
              return
            }
          }
          wx.chooseImage({
            count: 6 - currentSize, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            // sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              self.images.localId = self.images.localId.concat(res.localIds)
              if (window.__wxjs_is_wkwebview) {
                self.isIOS = true
                function readImages () {
                  wx.getLocalImgData({
                    localId: self.images.localId[currentSize],
                    success: function (res) {
                      var localData = res.localData
                      localData = localData.replace('jgp', 'jpeg')
                      self.images.iosLocalId.push(localData)
                      currentSize++
                      if (currentSize < self.images.localId.length) {
                        readImages()
                      }
                    },
                    fail: (res) => {
                      alert(res.errMsg)
                    }
                  })
                }
                readImages()
              }
              self._upload(currentSize)
            },
            fail: (err) => {
              console.log(err)
            }
          })
        }
      },
      _upload(i) {
        // var localId = localIds.shift()
        wx.uploadImage({
          localId: this.images.localId[i], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: (res) => {
            i++
            this.serverId.push(res.serverId) // 返回图片的服务器端ID
            this.serverIds = this.serverId.join(',')
            if (i < this.images.localId.length) {
              this._upload(i)
            }
          }
        })
      },
      delImage (index) {
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
      },
      delImageIOS (index) {
        this.images.iosLocalId.splice(index, 1)
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
      },
      preview (index) {
        wx.previewImage({
          current: this.images.localId[index], // 当前显示图片的http链接
          urls: this.images.localId // 需要预览的图片http链接列表
        })
      },
      saveImagesData() {
        const url = `${commonUrl.apihost}index.php/home/renthouse/add2`
        const data = {
          title: 'yn',
          content: 'hahahahah',
          serverIds: this.serverIds,
          areas_id: 204,
          openid: 'oHVoI1YFA6zvN1ymtrO4WrrRrmzA'
        }
        this.$http.post(url, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
          if (res.data.code === 200) {
            alert('发布成功')
            this.$router.back()
          }
          if (res.data.code === 400) {
            alert('发布失败')
          }
          if (res.data.code === 401) {
          }
        })
        // saveImages(serverIds).then(res => {
        //   if (res.code === 200) {
        //     this.url = res.data
        //   }
        // })
      }
    }
  }
</script>
